/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fxbank.netbeans.plugins.openfile;

import com.fxbank.netbeans.errors.RootException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;
import javax.swing.text.StyledDocument;
import org.netbeans.api.editor.EditorRegistry;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.modules.editor.NbEditorUtilities;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.cookies.EditorCookie;

import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.nodes.Node;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle.Messages;
import org.openide.util.actions.CallableSystemAction;

/**
 *
 * @author alexey
 */
@ActionID(category = "Edit",
id = "com.fxbank.netbeans.plugins.openfile.DispatcherFinderAction")
@ActionRegistration(displayName = "#CTL_DispatcherFinder")
@ActionReferences({
    @ActionReference(path = "Editors/text/x-jsp/Popup", position = 10)
})
@Messages("CTL_DispatcherFinder=Open Dispatcher")
public class DispatcherFinderAction implements  ActionListener {

    public DispatcherFinderAction() {
    }

//    private final EditorCookie context;
//
//    public FactoryFinderAction(EditorCookie context) {
//        this.context = context;
//    }

    
    
    @Override
    public void actionPerformed(ActionEvent ev) {
        
//        System.out.println(""+org.netbeans.lib.editor.util.swing.DocumentUtilities.getText(context.getDocument()));
 
        JTextComponent target = EditorRegistry.lastFocusedComponent();
        StyledDocument styledDoc = (StyledDocument) target.getDocument();
//        TokenHierarchy hi = TokenHierarchy.get(styledDoc);
//        TokenSequence<HTMLTokenId> ts = hi.tokenSequence(HTMLTokenId.language());
        
        //Start a new thread for opening the HTML document:
//        OpenHTMLThread run = new OpenHTMLThread(styledDocdoc, identifier);
//        RequestProcessor.getDefault().post(run);
        
        FileObject fo = NbEditorUtilities.getFileObject(styledDoc);
        FileObject pluginNameFO = fo.getParent();
        String pluginName = null;

        if (pluginNameFO != null && pluginNameFO.getParent() != null &&
                "plugins".equalsIgnoreCase(pluginNameFO.getParent().getName())){
            pluginName = pluginNameFO.getName();
        }
//      
        
        if (pluginName == null){
            JOptionPane.showMessageDialog(null, "Can't find plugin name of this JSP", "Not found", JOptionPane.WARNING_MESSAGE);
            return ;
        }
        

        try{
            Project project = FileOwnerQuery.getOwner(fo);
            System.out.println(""+project.getProjectDirectory().getPath());

            String pluginFolder = project.getProjectDirectory().getPath().concat(File.separator).
                    concat("src").concat(File.separator).concat("java").concat(File.separator).
                    concat("com").concat(File.separator).concat("fxclub").concat(File.separator).
                    concat("fxbank").concat(File.separator).concat("plugins").concat(File.separator).
                    concat(pluginName).concat(File.separator);
            
            File dispatcher = new File(pluginFolder+"Dispatcher.java");
            
            if (!dispatcher.isFile()) {
                //Возможно это Сервис
                dispatcher = new File(pluginFolder+"Service.java");
            }
            
            if (!dispatcher.isFile()) {
                //Возможно это Виджет
                dispatcher = new File(pluginFolder+"Widget.java");
            }
            
            if (!dispatcher.isFile()) {
                throw new RootException();
            }
            

            FileObject dispatcherFO = org.openide.filesystems.FileUtil.toFileObject(dispatcher);
            System.out.println("file object is valid = "+dispatcherFO.isValid());
            System.out.println("file is = "+dispatcher.isFile());
        
        
            DataObject newDo = DataObject.find(dispatcherFO); 
            final Node node = newDo.getNodeDelegate(); 
            Action a = node.getPreferredAction(); 
            if (a instanceof ContextAwareAction) { 
                   a = ((ContextAwareAction) a).createContextAwareInstance(node.getLookup()); 
            } 
            if (a != null) { 
                  a.actionPerformed(new ActionEvent(node, ActionEvent.ACTION_PERFORMED, "")); // NOI18N 
            }
        } catch (Throwable ex) {
            JOptionPane.showMessageDialog(null, String.format("Can't find Dispatcher/Service/Widget '%s'", pluginName), "Not found", JOptionPane.WARNING_MESSAGE);
            ex.printStackTrace();
        }
    }

//    @Override
//    public void performAction() {
//        //XXX
//    }
//
//    @Override
//    public String getName() {
//        return "Open Dispatcher";
//    }
//
//    @Override
//    public HelpCtx getHelpCtx() {
//        //XXX
//        return HelpCtx.DEFAULT_HELP;
//    }
    
}